package com.snow.auth.model;

import cn.hutool.core.util.StrUtil;
import com.snow.auth.entity.SystemTenant;
import com.snow.auth.entity.SystemUser;
import com.snow.exception.LoginUserNotFoundException;
import com.snow.model.ILoginUser;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Getter
@Setter
@Slf4j
public class WechatLoginUser implements ILoginUser {

    private Integer id;
    private Integer userId;
    private String name;
    private String avatar;
    private Date expireTime;
    private String phone;
    /**
     * openId当作登录账号
     */
    private String account;
    private String token;
    /**
     * 是否是允许切换管理员模式
     */
    private Boolean manager = false;
    /**
     * 租户信息
     */
    private TenantInfo tenantInfo;
    private List<String> permissions = new ArrayList<>();
    /**
     * 绑定房屋
     */
    private final String className = WechatLoginUser.class.getName();

    private SystemUserInfo managerInfo;
    @Override
    public Integer getDataScope() {
        return 0;
    }

    @Override
    public Integer getDeptId() {
        return 0;
    }


    @Override
    public Boolean isSystemAdmin() {
        return ILoginUser.super.isSystemAdmin();
    }

    @Override
    public Integer getTenantId() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes != null ? servletRequestAttributes.getRequest() : null;
        if (request == null) {
            log.error("当前线程无法获取Request，导致无法获取当前请求房屋所属租户");
            throw new LoginUserNotFoundException();
        }
        String tenantId = request.getHeader("x-tenantId");
        return Integer.parseInt(StrUtil.blankToDefault(tenantId, "0"));
    }

}
